import { useEffect, useState } from "react";

export const isFalsy = (value: unknown) => (value === 0 ? false : !value);
//在函数里，改变传入得对象本身是不好得
export const cleanObject = (object: object) => {
  //Object.assign({},object)
  const result = { ...object };
  Object.keys(result).forEach((key) => {
    // @ts-ignore
    const value = result[key];
    if (isFalsy(value)) {
      // @ts-ignore
      delete result[key];
    }
  });
  return result;
};

//自定义hooks方法 抽离
export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
  }, []);
};

// const debounce=(func,delay)=>{
//   let timeout;
//   return (...ma)=>{
//     if (timeout){
//       clearTimeout(timeout)
//     }
//     timeout=setTimeout(function(){
//       func()
//     },delay)
//   }
// }
// const log=debounce(()=>console.log('call'),5000)
// log()
// log()
// log()
export const useDebounce = <T>(value: T, delay?: number) => {
  const [debouncedValue, setDebounceValue] = useState(value);
  useEffect(() => {
    //每次value发生变化的时候，设置一个定时器
    const timeout = setTimeout(() => setDebounceValue(value), delay);
    //每次在上一个useEffect处理完以后在运行，负责清理上一次的定时任务
    return () => clearTimeout(timeout);
  }, [value, delay]);
  return debouncedValue;
};

export const useArray = <T>(initialArray: T[]) => {
  const [value, setValue] = useState(initialArray);
  return {
    value,
    setValue,
    add: (item: T) => setValue([...value, item]),
    clear: () => setValue([]),
    removeIndex: (index: number) => {
      const copy = [...value];
      copy.splice(index, 1);
      setValue(copy);
    },
  };
};
